<template>
  <div class="main">
    <!-- style="background-image: url(../../images/bg3.png)" -->
    <div
      v-if="welcome"
      class="welcome login-container"
      :style="backgourndStyle"
    >
      <!-- 在组件的click上有一个方法可以触发原生事件，添加修饰符 -->
      <van-circle
        v-model="currentTime"
        style="
          position: absolute;
          top: 10px;
          right: 10px;
          width: 44px;
          height: 44px;
        "
        size="56px"
        :rate="currentTime"
        v-on:click.native="closeWelcome"
        :text="`${time}s`"
      />
      <i class="icon"></i>
      <h1>萌币宠物坊</h1>
      <span class="title-des">优质商家推荐</span>
      <van-button round block type="info">进店了解更多 > </van-button>
      <div class="foot">
        <h3>宠物世界</h3>
        <span>精品宠物交易平台</span>
      </div>
    </div>
    <div v-else class="reglogin">
      <van-nav-bar title="用户登录" left-arrow />
      <article>
        <div class="top">
          <img src="../../images/log.jpg" alt="图片" class="log" />
          <span>手机号码登录</span>
        </div>

        <div class="ipt-box">
          <span>手机号</span>
          <input
            @blur="blurEvt"
            @focus="focusEvt"
            v-model="loginObj.phone"
            type="text"
            placeholder="输入注册手机号"
          />
          <van-icon name="cross" v-show="show" />
        </div>
        <div class="ipt-box">
          <span>验证码</span>
          <input v-model="loginObj.code" type="text" placeholder="输入验证码" />
          <!-- 获取验证码的标识就是文字 -->
          <span class="btn" @click="getVdtCode">{{ vdtText }}</span>
          <!-- <span class="btn">重新获取(60s)</span> -->
        </div>

        <div class="goReg">
          <span @click="goRegEvt">去注册？</span>
          <span>收不到验证码？</span>
        </div>
        <div class="feel">
          <van-checkbox v-model="remember" checked-color="#f5222d"
            >记住手机号？</van-checkbox
          >
          <van-checkbox v-model="auto" checked-color="#f5222d"
            >7天免登录？</van-checkbox
          >
        </div>

        <div style="margin: 16px">
          <van-button
            @click="loginEvt"
            round
            block
            type="info"
            :disabled="
              !/^1[3-9]{1}[0-9]{9}$/.test(loginObj.phone) ||
              loginObj.code.length !== 4 ||
              !checked
            "
            loading-text="登录中..."
            >登录</van-button
          >
        </div>
        <p>其他登录方式</p>
        <div class="icons">
          <van-icon class="icon" name="wechat" />
          <van-icon class="icon" name="alipay" />
        </div>
      </article>
      <van-checkbox class="deal" v-model="checked" checked-color="#ffd101"
        >登录代表已阅读并同意《用户协议》与《隐私注册》</van-checkbox
      >
    </div>
  </div>
</template>

<script>
// 单个接口引入
import {
  getUserInfoApi,
  getVdtCodeApi,
  loginApi,
  userInfoApi,
} from "../../apis/loginApi";

export default {
  data() {
    return {
      timer: null,
      time: 5,
      currentTime: 100,
      loginObj: {
        //手机号 验证码
        phone: "",
        code: "",
      },
      checked: false,
      welcome: true,
      auto: false, //免登录
      vdtText: "获取验证码",
      // 登录节流标识
      loading: false,
      autoFlag: "login",
      remember: false,
      show: false,
    };
  },

  // 广告栏背景图随机出现
  computed: {
    backgourndStyle: function () {
      // 存放要换的图片
      let imgs = [
        "https://img2.baidu.com/it/u=288087432,301955349&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=889",
        "https://img1.baidu.com/it/u=440382770,4170816405&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=889",
        "https://img1.baidu.com/it/u=1016481357,1142757898&fm=253&fmt=auto&app=138&f=JPEG?w=281&h=500",
        "https://img2.baidu.com/it/u=1711184725,843351254&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=889",
      ];
      let imgName = imgs[Math.floor(Math.random() * 4)]; //进行计算随机
      let style =
        "background-image:url('" + imgName + "'); background-repeat: round; ";
      return style;
    },
  },

  // 在用户进入系统的时候，开始获取缓存，根据缓存不同走不同的业务
  created() {
    // 在欢迎界面需要一个倒计时
    this.timer = setInterval(() => {
      if (this.currentTime > 0) {
        this.currentTime -= 1;
        this.time = Math.ceil(this.currentTime / 20);
      } else {
        // 倒计时到了就关闭欢迎页面
        this.welcome = false;
      }
    }, 50);
    // 读取免登录缓存  --auto-text
    let autoText = localStorage.getItem("auto-text");
    // 如果有缓存则发送自动登录接口
    if (!!autoText) {
      setTimeout(() => {
        this.autoFlag = "success";
      }, 2000);
    } else {
      // 读取手机号缓存
      let userPhone = localStorage.getItem("user-phone");
      // 如果手机号存在 -- 给登录数据的phone赋值并且要把记住手机号的标识置为真
      if (!!userPhone) {
        this.loginObj.phone = userPhone;
        this.remember = true;
      }
      // 登录失败
      this.autoFlag = "error";
    }
  },
  methods: {
    blurEvt() {
      this.show = false;
    },
    focusEvt() {
      this.show = true;
    },
    // autoFlag = 免登录进行中 login、登录成功 success、登录失败 error
    closeWelcome() {
      // 免登录进行中 --不执行任何业务
      if (this.autoFlag === "login") return;

      // 只有免登录完成以后都需要关闭定时器
      if (this.autoFlag === "success") {
        this.$router.push("/home");
      } else {
        this.welcome = false;
      }
    },
    goRegEvt() {
      this.$router.push("/register");
    },
    async loginEvt() {
      // 开启节流标识
      this.loading = true;

      // 不需要做手机和验证码校验
      // 直接发起请求
      let result = await loginApi(this.loginObj);

      // 先校验是否登录成功
      if (result.code !== 200) {
        this.$toast.fail("登录失败，请重试！");
        this.loading = false;
        return;
      }

      // 成功 调用dispatch commit方法缓存token --需要引入store实例
      this.$store.commit("common/setToken", result.data.token);
      // 调用获取用户信息的接口，一定要保证vuex中有token数据，所以应该先缓存token，然后发起请求
      let user = await userInfoApi(result.data.id);

      // 缓存用户信息到vuex中
      this.$store.commit("common/setUserInfo", result.data);

      // 判断是否同意免登录
      if (this.auto) {
        localStorage.setItem("auto-text", result.data.token);
      } else {
        localStorage.removeItem("auto.text");
      }

      // 判断是否同意记住手机号
      if (this.remember) {
        localStorage.setItem("user-phone", this.loginObj.phone);
      } else {
        localStorage.removeItem("user-phone");
      }

      this.$router.push("/home");
    },

    // 获取验证码的方法
    async getVdtCode() {
      // 判断节流是否存在，存在不能发起请求
      if (this.vdtText !== "获取验证码") return;

      // 判断手机号输入是否正确
      if (!/^1[3-9]{1}[0-9]{9}$/.test(this.loginObj.phone)) {
        this.$toast({
          message: "请输入正确的用户名",
          position: "bottom",
        });
        return;
      }

      // 手机号校验没问题，需要设置节流标识
      this.vdtText = "获取中...";

      let result = await getVdtCodeApi(this.loginObj.phone);
      if (result.code !== 200) {
        this.$toast.fail("获取验证码失败，请重试！");
        //  重置节流标识
        this.vdtText = "获取验证码";
        return;
      }

      // 提示用户验证码获取成功
      this.$toast.success(`验证码获取成功，验证码：${result.data.code}`);

      // 做一个倒计时 --常用的是 setTimeout + 递归 实现
      // 需要一个开始的时间
      this.loopTimer(Date.now());
    },

    // 递归实现倒计时
    loopTimer(_st) {
      // 获取当前时间，然后减去开始时间得到过去的时间
      let _pt = Math.ceil((Date.now() - _st) / 1000);
      this.vdtText = `重新获取(${5 - _pt}s)`;
      setTimeout(() => {
        // 实现递归
        // 判断已经过去的时间要小于等待时间
        if (_pt < 5) {
          this.loopTimer(_st);
        } else {
          this.vdtText = "获取验证码";
        }
      }, 100);
    },
  },
};
</script>

<style lang="less">
@import "../../style/common.less";

.feel {
  display: flex;
  justify-content: space-between;
  padding: 0 16px;
  margin-top: 10px;
}
.main {
  position: relative;
  width: 100%;
  height: 100%;
  .welcome {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 100%;
    background-image: url(../../images/bg.png);
    background-size: 100%;


    > h1 {
      letter-spacing: 12px;
      margin-top: 37px;
    }
    > .title-des {
      margin-bottom: 360px;
      color: #c9ac2c;
      font-size: 18px;
      letter-spacing: 10px;
    }

    .van-button--info {
      color: #fff;
      background-color: rgba(75, 72, 72, 0.527);
      border: none;
    }
    .van-button--block {
      display: block;
      width: 85%;
      height: 50px;
      margin-bottom: 15px;
    }
    .foot {
      width: 100%;
      height: 20%;
      background-color: rgba(255, 255, 255, 0.787);
      border-radius: 10px 10px 0 0;
      text-align: center;
      h3 {
        font-style: italic;
        letter-spacing: 8px;
      }
      span {
        color: #918585;
        font-size: 13px;
        letter-spacing: 2px;
      }
    }
  }
  .deal {
    position: absolute;
    bottom: 50px;
    padding: 0 15px;
    color: #999;
    font-size: 14px;
  }
  .van-circle {
    width: 44px;
    height: 44px;
  }
  .van-circle__text {
    color: #fff;
  }
  .van-circle__hover {
    stroke: #ffd101;
  }
}

.reglogin {
  .ipt-box {
    padding: 10px 0;
    margin-bottom: 16px;
    margin-left: 24px;
    input {
      padding-bottom: 3px;
      background: transparent;
      margin-left: 20px;
      border: none;
      outline: none;
      text-indent: 12px;
      font-size: 0.8rem;
      border-bottom: 1px solid rgb(190, 185, 185);
      // &和input同级样式
      &::-webkit-input-placeholder {
        font-size: 0.75rem;
        color: #666;
      }
    }

    .btn {
      display: inline-block;
      border-left: 1px solid #eaeaea;
      margin-left: 5px;
      padding: 5px 10px;
      font-size: 0.7rem;
      text-align: center;
      color: #fff;
      background-color: #ffd101;
      border-radius: 8px;
    }
  }

  .van-nav-bar__title {
    font-size: 18px;
    font-weight: 600;
  }
  .van-nav-bar .van-icon {
    color: rgb(24, 22, 22);
    font-weight: 600;
  }
  > article {
    > .top {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin: 40px 0 20px 0;
      > img {
        width: 70px;
      }
      > span {
        font-weight: 600;
        font-size: 15px;
        margin-top: 8px;
      }
    }
    > .goReg {
      display: flex;
      justify-content: space-between;
      padding: 0 18px;
    }
    > p {
      margin: 50px 0 20px 0;
      color: #999;
      font-size: 15px;
      text-align: center;
    }
    > .icons {
      display: flex;
      justify-content: space-around;
      padding: 0 50px;
      > .icon {
        width: 45px;
        height: 45px;
        background-color: #666;
        border-radius: 50%;
        text-align: center;
        line-height: 45px;
        font-size: 28px;
        color: #ffd101;
      }
    }
  }

  .van-button--primary {
    color: #ffd101;
    background: none;
    border: none;
  }
  .van-cell__value {
    padding-left: 5px;
    border-bottom: 1px solid #eaeaea;
  }
  .van-button--info {
    color: #000;
    background-color: #ffd101;
    border: none;
  }
}
</style>
